<?php
/* 	Description */

class Form_Validator_UniqueDBTableEntryValidator extends Zend_Validate_Abstract 
{
	
    const NOT_UNIQUE = 'EntryNotUnique';

    protected $_messageTemplates = array(
        self::NOT_UNIQUE => 'The value already exists'
    );

	protected $table;
	protected $field;

    /**
     * Constructor of this validator
     *
     * The argument to this constructor is the third argument to the elements' addValidator
     * method.
     *
     * @param array|string $dbinfo = {TableName , FieldName}
     */
    public function __construct($table, $field) 
    {
		$this->table = $table;
		$this->field = $field;
    }

    /**
     * Check if the element using this validator is valid
     *
     * This method will check if the value exist in table Table
     * under field FIELD, succeeds if the value does not exist
     * 
     * @param $value string
     * @param $context array All other elements from the form
     * @return boolean Returns true if the element is valid
     */
    public function isValid($value) 
    {
    	// Fail if a user with that name already exist
        $row = $this->table->fetchRow($this->field."='".$value."'");
        if ($row != null) {
        	$this->_error(self::NOT_UNIQUE);
        	return false;
        }
        
        return true;        
    }
}